<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('Controller', 'Controller');
App::uses('MyAuthenticate', 'Controller/Component/Auth');
App::uses('Folder', 'Utility');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
	
	public $components = array('Session');
	public  $uses = array("User");
	
	public function loggedIn(){
		$this->autoRender = false;
		
		// case 1: khong truyen tham so trong request
		if (empty($this->request->data['userid']) || empty($this->request->data['accesstoken'])){
			return false;
		}
		
		// case 2: chua luu session cua userid
		if (!$this->Session->check("user".$this->request->data["userid"])){
			return false;
		}
		$userid = $this->request->data["userid"];
		$user = $this->User->find("first",array("conditions" => array("id" =>$userid),"recursive" => -1,
				"fields" => array("User.accesstoken")));
		
		// case 3: da luu session nhung khong chinh xac
		$token = $this->request->data["accesstoken"];
		if($token != $user["User"]["accesstoken"]){
			return false;
		}
		
		// neu pass chung thuc da login
		
		return true;
	}
	
	public function beforeFilter(){
		$this->autoRender = false;
		if($this->request->params["controller"] != "users"){
			if (!$this->loggedIn()){
				$data = array("status_code" => -1, "message" => "You have to login first","entity" => array());
				//die (json_encode($data));
			}
		}
		
	}
}

